/*
    Copyright 2011 Wira Mulia, David Fritz

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * ControlFrame.java
 *
 * Created on 18 Mar 11, 13:56:30
 */

package plpbotcontrol;

import java.net.Socket;
import java.util.HashSet;
import java.awt.event.KeyEvent;

/**
 *
 * @author wira
 */
public class ControlFrameWira extends javax.swing.JFrame {

    private HashSet<Integer> keyCombo;
    private int firstKey;

    /** Creates new form ControlFrame */
    public ControlFrameWira() {
        initComponents();

        keyCombo = new HashSet<Integer>();

        try {

        Global.baseStation = new Socket(Global.baseStationHost, Global.baseStationPort);

        (new SenderThreadWira()).start();

        } catch(Exception e) {
            System.err.println("control frame exception: " + e);
            System.exit(-1);
        }

        comboOffset.setValue(30);
    }

    public int getS1Value() {
        return S1.getValue();
    }

    public int getS2Value() {
        return S2.getValue();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        S1 = new javax.swing.JSlider();
        S2 = new javax.swing.JSlider();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        stop = new javax.swing.JButton();
        comboOffset = new javax.swing.JSlider();
        jLabel3 = new javax.swing.JLabel();
        zeroTurn = new javax.swing.JSlider();
        jLabel4 = new javax.swing.JLabel();

        jButton1.setText("jButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        S1.setMaximum(63);
        S1.setMinimum(-63);
        S1.setValue(0);

        S2.setMaximum(63);
        S2.setMinimum(-63);
        S2.setValue(0);

        jLabel1.setText("S1");

        jLabel2.setText("S2");

        stop.setText("OH NO, STOP!!!");
        stop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopActionPerformed(evt);
            }
        });
        stop.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                stopKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                stopKeyReleased(evt);
            }
        });

        comboOffset.setMaximum(63);
        comboOffset.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                comboOffsetStateChanged(evt);
            }
        });

        jLabel3.setText("Turn radius");

        zeroTurn.setMaximum(63);
        zeroTurn.setValue(30);
        zeroTurn.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                zeroTurnStateChanged(evt);
            }
        });

        jLabel4.setText("Zero radius turn speed");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(zeroTurn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(comboOffset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(4, 4, 4)
                        .addComponent(jLabel3))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(S1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(S2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(stop, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(S1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(S2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(stop, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(zeroTurn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(comboOffset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void stopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopActionPerformed
        S1.setValue(0);
        S2.setValue(0);
    }//GEN-LAST:event_stopActionPerformed

    private void stopKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_stopKeyPressed
        keyCombo.add(evt.getKeyCode());

        // adjust turn offset, independent of other keys
        if(evt.getKeyCode() == KeyEvent.VK_Q) {
            if((comboOffset.getValue() - Global.turnOffsetIncrement) >= 0)
                comboOffset.setValue(comboOffset.getValue() - Global.turnOffsetIncrement);
            else
                comboOffset.setValue(0);
        }
        else if(evt.getKeyCode() == KeyEvent.VK_E) {
            if((comboOffset.getValue() + Global.turnOffsetIncrement) <= comboOffset.getMaximum())
                comboOffset.setValue(comboOffset.getValue() + Global.turnOffsetIncrement);
            else
                comboOffset.setValue(comboOffset.getMaximum());
        }

        // a key is pressed
        else if(keyCombo.size() == 1) {
            firstKey = evt.getKeyCode();
            switch(evt.getKeyCode()) {
                case KeyEvent.VK_W:
                    S1.setValue(63);
                    S2.setValue(63);
                    break;

                case KeyEvent.VK_S:
                    S1.setValue(-63);
                    S2.setValue(-63);
                    break;

                case KeyEvent.VK_A:
                    S1.setValue(0 - Global.zeroTurnOffset);
                    S2.setValue(Global.zeroTurnOffset);
                    break;

                case KeyEvent.VK_D:
                    S1.setValue(Global.zeroTurnOffset);
                    S2.setValue(0 - Global.zeroTurnOffset);
                    break;
            }

        // second key is pressed, adjust for W+A, W+D, and S+A, S+D
        } else if(keyCombo.size() == 2) { 
            switch(firstKey) {
                case KeyEvent.VK_W:
                    if(evt.getKeyCode() == KeyEvent.VK_A) {
                        S1.setValue(63 - Global.comboKeyOffset);
                        S2.setValue(63);
                    }
                    else if(evt.getKeyCode() == KeyEvent.VK_D)  {
                        S1.setValue(63);
                        S2.setValue(63 - Global.comboKeyOffset);
                    }
                    break;

                case KeyEvent.VK_S:
                    if(evt.getKeyCode() == KeyEvent.VK_A) {
                        S1.setValue(-63);
                        S2.setValue(-63 + Global.comboKeyOffset);
                    }
                    else if(evt.getKeyCode() == KeyEvent.VK_D)  {
                        S1.setValue(-63 + Global.comboKeyOffset);
                        S2.setValue(-63);
                    }
                    break;

                case KeyEvent.VK_A:
                    if(evt.getKeyCode() == KeyEvent.VK_W) {
                        S1.setValue(63 - Global.comboKeyOffset);
                        S2.setValue(63);
                    }
                    else if(evt.getKeyCode() == KeyEvent.VK_S)  {
                        S1.setValue(-63);
                        S2.setValue(-63 + Global.comboKeyOffset);
                    }
                    break;

                case KeyEvent.VK_D:
                    if(evt.getKeyCode() == KeyEvent.VK_W) {
                        S1.setValue(63);
                        S2.setValue(63 - Global.comboKeyOffset);
                    }
                    else if(evt.getKeyCode() == KeyEvent.VK_S)  {
                        S1.setValue(-63 + Global.comboKeyOffset);
                        S2.setValue(-63);
                    }
                    break;
            }

        // if the user presses more than 2 keys, what the hell, ignore
        // ... button masher ...
        } else {

        }
    }//GEN-LAST:event_stopKeyPressed

    private void stopKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_stopKeyReleased
        keyCombo.remove(evt.getKeyCode());

        // if we're down to no key pressed, stop
        if(keyCombo.isEmpty())
            stopActionPerformed(null);

        // revert back to one-key-pressed configuration if not
        if(keyCombo.size() == 1) {
            switch(firstKey) {
                case KeyEvent.VK_W:
                    S1.setValue(63);
                    S2.setValue(63);
                    break;

                case KeyEvent.VK_S:
                    S1.setValue(-63);
                    S2.setValue(-63);
                    break;

                case KeyEvent.VK_A:
                    S1.setValue(0 - Global.zeroTurnOffset);
                    S2.setValue(Global.zeroTurnOffset);
                    break;

                case KeyEvent.VK_D:
                    S1.setValue(Global.zeroTurnOffset);
                    S2.setValue(0 - Global.zeroTurnOffset);
                    break;
            }
        }
    }//GEN-LAST:event_stopKeyReleased

    private void comboOffsetStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_comboOffsetStateChanged
        Global.comboKeyOffset = comboOffset.getValue();
    }//GEN-LAST:event_comboOffsetStateChanged

    private void zeroTurnStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_zeroTurnStateChanged
        Global.zeroTurnOffset = zeroTurn.getValue();
    }//GEN-LAST:event_zeroTurnStateChanged



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JSlider S1;
    private javax.swing.JSlider S2;
    private javax.swing.JSlider comboOffset;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JButton stop;
    private javax.swing.JSlider zeroTurn;
    // End of variables declaration//GEN-END:variables

}


class SenderThreadWira extends Thread {
    @Override
    public void run() {
        try {

        while(true) {
            Global.baseStation.getOutputStream().write(0x7F);
            Global.baseStation.getOutputStream().write(Global.controlFrameWira.getS1Value() + 64);
            Global.baseStation.getOutputStream().write(Global.controlFrameWira.getS2Value() + 192);
            Thread.sleep(Global.senderRate);
        }

        } catch(Exception e) {
            System.err.println("senderThread exception: " + e);
        }
    }
}